<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace Haozing\FastCore\Exception\Handler;

use Haozing\FastCore\Log\RequestIdHolder;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use function Hyperf\Support\env;

class CommonExceptionHandler extends ExceptionHandler
{
    public function __construct(protected StdoutLoggerInterface $logger)
    {
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {

        $file = explode('/', $throwable->getFile());
        //获取数组最后的一个
        $file = end($file);
        $error = sprintf('%s in %s[%s]', $throwable->getMessage(), $throwable->getFile(), $throwable->getLine());
        $this->logger->error($error);
        $this->logger->error($throwable->getTraceAsString());


        $data = responseDataFormat($throwable->getCode(), $throwable->getMessage());
        $data['requestId'] = RequestIdHolder::getId();
        $data['error'] = sprintf('The error is located at line [%s] of the [%s] file', $throwable->getLine(),$file);
        $appEnv = env('APP_ENV', 'dev');
        if ($appEnv == 'dev') {
            $data['trace'] = $throwable->getTrace();
        }
        $dataStream = new SwooleStream(json_encode($data, JSON_UNESCAPED_UNICODE));
        ## 阻止异常冒泡
        $this->stopPropagation();
        return $response->withHeader('Server', 'fast-core')
            ->withAddedHeader('Content-Type', 'application/json;charset=utf-8')
            ->withStatus(200)
            ->withBody($dataStream);
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
